import axios from "axios";
import errorCode from "@/utils/errorCode";
import { tansParams } from "@/utils/common";
import { userStore } from "@/store/index.js";
const store = userStore();
import { Toast } from "vant";
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const env = import.meta.env;

const opts = {
  baseURL: env.VITE_BASE_API,
  timeout: 999999999,
  errorTip: true,
};

export const service = axios.create(opts);

service.interceptors.request.use(
  (config) => {
    const isToken = (config.headers || {}).isToken === false;
    if (localStorage.getItem("token") && !isToken) {
        config.headers["Authorization"] =
            "Bearer " + localStorage.getItem("token"); // 让每个请求携带自定义token 请根据实际情况自行修改
    }

    if (config.data?.params) {
      let url = config.url + "?" + tansParams(config.data?.params);
      url = url.slice(0, -1);
      config.data = undefined;
      config.url = url;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (Object.prototype.toString.call(response.data) === "[object Blob]") {
      return response;
    }
    const { data, config } = response;
    const { code, success, msg } = data;
    const message =
      response.data.msg ||
      response.data.message ||
      errorCode[code] ||
      errorCode["default"];
    // 增加失败判断
    data.fail = code !== "200" && success !== true;
    if (code === "403") {
      // todo: 异常反馈
      Toast.fail(msg || "登录过期");
      window.location.href = "/#/login";
      return Promise.reject(data);
    } else if (code !== "200" && config.errorTip) {
      Toast.fail(message || "接口异常");
      return Promise.reject(data);
    }
    return data;
  },
  (error) => {
    let { message } = error;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    // todo: 异常反馈

    Toast.fail(message);
    return Promise.reject(error);
  }
);

export default service;
